import Vue from "vue"
import VueRouter from "vue-router"
Vue.use(VueRouter)

//引入路由组件，非路由懒加载
// import Home from '@/pages/Home'  //Home组件路由懒加载
import Search from '@/pages/Search'
import Register from '@/pages/Register'
import Login from '@/pages/Login'
import store from "@/store"

//重写VueRouter的push、reaplce方法，以避免多次编程式路由跳转的报错
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function (routeObj, resolve = () => { }, reject = () => { }) {
    originPush.call(this, routeObj, resolve, reject)  //注意这里必须用call，如果不用，则调用函数的对象是windows，而不是VueRouter实例
}
VueRouter.prototype.replace = function (routeObj, resolve = () => { }, reject = () => { }) {
    originReplace.call(this, routeObj, resolve, reject)
}

//配置路由
let router = new VueRouter({
    routes: [
        {
            path: '/home',
            component: ()=>import('@/pages/Home'),  //路由懒加载：访问该路由时才引入
            meta: { show: true }
        },
        {
            name: 'search',
            path: '/search/:keyword?',  //params参数独有的展位，?表示可传可不传
            component: Search,
            meta: { show: true }
        },
        {
            path: '/login',
            component: Login,
            meta: { show: false }
        },

        {
            path: '/register',
            component: Register,
            meta: { show: false }
        },
        //重定向到首页
        {
            path: '*',
            redirect: '/home'
        }

    ]
})

router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token
    let name = store.state.user.name

    if (token) {  //已经登入
        if (to.path == '/login') {  //去login，不能去停留在首页
            next('./home')
        } else {  //登入，去的不是login
            if(name){  //如果用户名已经有
                next()
            }else{  //没有用户信息，派发actions获取用户信息
                try {
                    await store.dispatch('user/getUserInfo')
                    next()
                } catch (error) {
                    //token过期了，清除token
                    await store.dispatch('user/Logout')
                    next('/login')
                }
            }
        }
    } else {  //未登入
        next()
    }
})

export default router